package happy.town.case_user;

import happy.town.case_student_pro.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @BelongsProject: case_user
 * @BelongsPackage: happy.town.case_user
 * @Author: ByHappy  (Email:1300985301@qq.com)
 * @CreateTime: 2023-08-08 01:50
 * @Description:
 * @Version: 1.0
 **/
public class UserDaoImpl implements UserDao {
    /*
         使用PreparedStatement的登录方法，解决注入攻击
    */
    @Override
    public User findByLoginNameAndPassword(String loginName, String password) {
        //定义必要信息
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = null;
        try {
            //1.获取连接
            conn = JDBCUtils.getConnection();
            //2.创建操作SQL对象
            String sql = "SELECT * FROM user WHERE loginname=? AND password=?";
            pstm = conn.prepareStatement(sql);
            //3.设置参数
            pstm.setString(1, loginName);//设置第一个?参数
            pstm.setString(2, password);//设置第二个?参数
            System.out.println(sql);
            //4.执行sql语句，获取结果集
            rs = pstm.executeQuery();
            //5.获取结果集
            if (rs.next()) {
                //6.封装
                user = new User();
                user.setUid(rs.getString("uid"));
                user.setUcode(rs.getString("ucode"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setGender(rs.getString("gender"));
                user.setDutydate(rs.getDate("dutydate"));
                user.setBirthday(rs.getDate("birthday"));
                user.setLoginname(rs.getString("loginname"));
            }
            //7.返回
            return user;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close(conn, pstm, rs);
        }
    }
}

